using MySql.Data.MySqlClient;
using System.Text;

namespace Tools.Android
{
    public class VSCodeEntityConverter
    {


        public string ConvertToVSCodeEntitys(string connectionString, string tableName, string dataBase)
        {
            var columns = GetTableColumns(connectionString, tableName, dataBase);

            var sb = new StringBuilder();
            string className = ToPascalCase(tableName);




            sb.AppendLine("/* tslint:disable */");
            sb.AppendLine("/* eslint-disable */");
            sb.AppendLine("/**");
            sb.AppendLine(" * Admin.NET 通用权限开发平台");
            sb.AppendLine(" * 让 .NET 开发更简单、更通用、更流行。整合最新技术，模块插件式开发，前后端分离，开箱即用。<br/><u><b><font color='FF0000'> 👮不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！</font></b></u>");
            sb.AppendLine(" *");
            sb.AppendLine(" * OpenAPI spec version: 1.0.0");
            sb.AppendLine(" * ");
            sb.AppendLine(" *");
            sb.AppendLine(" * NOTE: This class is auto generated by the swagger code generator program.");
            sb.AppendLine(" * https://github.com/swagger-api/swagger-codegen.git");
            sb.AppendLine(" * Do not edit the class manually.");
            sb.AppendLine(" */");
            sb.AppendLine("");

            // 类注释
            sb.AppendLine("/**");
            sb.AppendLine($" *  ");
            sb.AppendLine($" *  {tableName}");
            sb.AppendLine($" *  @export");
            sb.AppendLine($" *  @interface {className}Entity");
            sb.AppendLine(" */");
            sb.AppendLine("");

            // 类注解
            sb.AppendLine($"export interface {className}Entity {{");
            sb.AppendLine("");


            string[] _replaceWords = { "Id", "CreateTime", "UpdateTime", "CreateUserId", "CreateUserName", "UpdateUserId", "UpdateUserName" };

            //                    var res = _dirtyWords.Any(x => trNode.InnerText.Contains(x));       //true


            // 处理每个字段
            foreach (var col in columns)
            {
                string fieldName = FirstCharToLower(col.ColumnName);
                string javaType = MapType(col.DataType);


                //var res = _replaceWords.Any(x => fieldName.ToLower().Contains(x.ToLower()));
                //if (!res)
                //{
                // 字段注释


                sb.AppendLine("/**");
                sb.AppendLine($" * {col.DataDesc} ");
                sb.AppendLine($" * ");
                //sb.AppendLine($" * @Type{"{ col.DataDesc} });
                sb.AppendLine(" * Type{" + javaType + "}");
                sb.AppendLine($" * @memberof {className}Entity ");
                sb.AppendLine(" */");

                // 字段定义
                //    id?: number;
                if (col.IsNull)
                {
                    sb.AppendLine($"    {fieldName}? : {javaType}|null ;");
                }
                else
                {
                    sb.AppendLine($"    {fieldName} : {javaType} ;");
                }
                sb.AppendLine();
                //}
            }

            #region 生成Getter/Setter
            // 生成Getter/Setter

            //foreach (var col in columns)
            //{
            //    string fieldName = ToCamelCase(col.ColumnName);
            //    string filedName2 = FirstCharToLower(col.ColumnName);
            //    string capitalized = Capitalize(fieldName);
            //    string javaType = MapType(col.DataType);

            //    var res = _replaceWords.Any(x => fieldName.ToLower().Contains(x.ToLower()));
            //    if (!res)
            //    {


            //        // Getter
            //        sb.AppendLine($"    public {javaType} get{capitalized}() {{");
            //        sb.AppendLine($"        return this.{filedName2};");
            //        sb.AppendLine("    }");
            //        sb.AppendLine();

            //        // Setter
            //        sb.AppendLine($"    public void set{capitalized}({javaType} {filedName2}) {{");
            //        sb.AppendLine($"        this.{filedName2} = {filedName2};");
            //        sb.AppendLine("    }");
            //        sb.AppendLine();
            //    }
            //}


            #endregion

            sb.AppendLine("}");
            return sb.ToString();
        }

        public static string FirstCharToLower(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            if (input.Length == 1)
                return input.ToLower();

            return char.ToLower(input[0]) + input.Substring(1);
        }

        private List<ColumnInfo> GetTableColumns(string connStr, string tableName, string dataBase)
        {
            var columns = new List<ColumnInfo>();

            using var conn = new MySqlConnection(connStr);
            conn.Open();


            // 查询列信息
            string sql = $@"SELECT 
                            COLUMN_NAME, 
                            DATA_TYPE,
                            COLUMN_COMMENT,
                            COLUMN_KEY = 'PRI',
                            EXTRA LIKE '%auto_increment%',IS_NULLABLE
                            FROM INFORMATION_SCHEMA.COLUMNS 
                            WHERE TABLE_NAME = '{tableName}' AND TABLE_SCHEMA ='{dataBase}'";

            using var cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.AddWithValue($"{tableName}", tableName);

            using var reader = cmd.ExecuteReader();
            while (reader.Read())
            {

                columns.Add(new ColumnInfo
                {
                    ColumnName = reader.GetString(0),
                    DataType = reader.GetString(1),
                    DataDesc = reader.GetString(2),
                    IsPrimaryKey = reader.GetUInt64(3) == 1 ? true : false,
                    IsAutoIncrement = reader.GetUInt64(4) == 1 ? true : false,
                    IsNull = reader.GetString(5) == "YES" ? true : false,
                });
            }

            return columns;
        }

        private string MapType(string mysqlType)
        {
            // 去除长度信息（如VARCHAR(255)）
            string baseType = mysqlType.Split('(')[0];
            return DictionaryMappings.VsCodeDictionaryTypeMap.TryGetValue(baseType, out string javaType)
                ? javaType : "Object";
        }

        private string ToPascalCase(string input)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string part in input.Split('_'))
            {
                if (part.Length > 0)
                    sb.Append(char.ToUpper(part[0]) + part.Substring(1).ToLower());
            }
            return sb.ToString();
        }

        private string ToCamelCase(string input)
        {
            string pascal = ToPascalCase(input);
            return char.ToLower(pascal[0]) + pascal.Substring(1);
        }

        private string Capitalize(string input)
            => char.ToUpper(input[0]) + input.Substring(1);
    }


}